//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    internal sealed class Ref3DToken : FormulaToken
    {
        
        
        public Ref3DToken(AccessorType type)
        {
            _token = new RefToken(type);
        }

        public Ref3DToken(ushort index, RefToken token)
        {
            this._index = index;
            this._token = token;
        }

        private readonly RefToken _token;
        private ushort _index;

        public override ushort GetLength(FormulaReadContextType formulaReadContextType)
        {
            switch (formulaReadContextType)
            {
                case FormulaReadContextType.Default:
                    return 6;
                    case FormulaReadContextType.ExternName:
                    return 8;
                    default:
                    // Contract.Assert(false);
                    throw new NotSupportedException();
            }
        }

        internal override void ReadContent(FormulaReadContext context)
        {
            _index = context.ReadUInt16();
            _token.ReadContent(context);
        }
        public override void WriteContent(FormulaWriteContext context)
        {
            context.WriteUInt16(_index);
            _token.WriteContent(context);
        }

        public override FormulaTokenId TokenId
        {
            get {
                switch (_token.Type)
                {
                        case AccessorType.Array:
                        return FormulaTokenId.Ref3dA;
                        case AccessorType.Reference:
                        return FormulaTokenId.Ref3d;
                        case AccessorType.Value:
                        return FormulaTokenId.Ref3dV;
                    default:
                        throw new NotSupportedException();
                } }
        }

        internal override Expression GetExpression(FormulaEvaluationContext context)
        {
            var worksheet =  context.WorkbookContext.GetExternalSheet(_index);
            if (worksheet == null)
                return new ErrorExpression(Errors.RefError);
            //var worksheet = context.Workbook.Sheets[_index] as Worksheet;
            return _token.GetExpression(
                new FormulaEvaluationContext(context.WorkbookContext, context.Arguments, worksheet)); //\\
        }
    }
}